In [1]:
import pdb
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
from datetime import datetime
import pdb
import time

%matplotlib inline

In [2]:
'''Data loading'''
f_names_national = [
    '2012 Conso Prod.csv',
    '2013 Conso Prod.csv',
    '2014 Conso Prod.csv',
    '2015 Conso Prod.csv'
]

datas = []
data_news = []
for f_name in f_names_national:
#     print(f_name)
    data = pd.read_csv('data/'+ f_name, delimiter='\t', encoding = "ISO-8859-1")
    pd.set_option('max_columns', 100)
    headers = list(data)
    data = data[data.Consommation.notnull()]
    data = data[data.Date.notnull()]
    data['timestamp'] = [str(d) + ' ' + str(t) for d, t in zip(data['Date'].values, data['Heures'].values)]
    data['timestamp'] = pd.to_datetime(data['timestamp'], format='%Y-%m-%d %H:%M')
    datas.append(data)

data_final = pd.concat(datas).reset_index()


/home/benlet/anaconda3/lib/python3.5/site-packages/IPython/core/interactiveshell.py:2717: DtypeWarning: Columns (18,19,20,21,22) have mixed types. Specify dtype option on import or set low_memory=False.
  interactivity=interactivity, compiler=compiler, result=result)
/home/benlet/anaconda3/lib/python3.5/site-packages/IPython/core/interactiveshell.py:2717: DtypeWarning: Columns (18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35) have mixed types. Specify dtype option on import or set low_memory=False.
  interactivity=interactivity, compiler=compiler, result=result)

In [3]:
# Sorting values : le premier élement du data set est le plus récent : 
# y(t), y(t-1) etc... 
data_final = data_final.sort_values(by=['Date','Heures'], ascending=[False,False])

'''tau : paramètre de périodicité'''
tau = 10 # 48 : on considère une corrélation de 24h. On pourrait prendre tau = 1 an 
            # afin de correler les données avec les données de l'année passée


data_mean = np.mean(data_final['Consommation'].values)
data_maxmin = np.max(data_final['Consommation'].values) - np.min(data_final['Consommation'].values)

def data_labels(dataframe=data_final, field='Consommation', tau = tau):
    X = dataframe[field].values
    
    ''' Normalization '''
    X = (X - data_mean) / data_maxmin
    ''' Rolling vector X'''
    X_ = np.stack([np.roll(X,i) for i in range(tau+1)], axis=1)

    labels = X_[:,:1]
    data = X_[:,1:]
    return data, labels

In [4]:
# Creating the training set and the crossvalidation set.
# two years of training, 1 year for cv 
n_samples = data_final.Consommation.values.shape[0]
data_train, labels_train = data_labels(dataframe = data_final[(data_final['Date'] <= '2015-01-31') & (data_final['Date'] > '2014-12-31')])
data_test, labels_test = data_labels(dataframe = data_final[(data_final['Date'] > '2015-01-31') & (data_final['Date'] <= '2016-01-01')])

ANN - Simple MLP


In [5]:
from keras.models import Sequential
from keras.layers import Dense


Using TensorFlow backend.

In [6]:
%%time
# create and fit Multilayer Perceptron model
from keras import optimizers

model = Sequential()
model.add(Dense(15, input_dim=tau, activation='relu'))
model.add(Dense(1))
# optimizer = optimizers.SGD(lr=0.1, momentum=0.9, nesterov=True)
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(data_train, labels_train, nb_epoch=20, batch_size=10, verbose=2)


Epoch 1/20
0s - loss: 0.0095
Epoch 2/20
0s - loss: 0.0020
Epoch 3/20
0s - loss: 0.0013
Epoch 4/20
0s - loss: 9.0517e-04
Epoch 5/20
0s - loss: 7.2106e-04
Epoch 6/20
0s - loss: 5.8873e-04
Epoch 7/20
0s - loss: 4.7790e-04
Epoch 8/20
0s - loss: 4.0559e-04
Epoch 9/20
0s - loss: 3.7872e-04
Epoch 10/20
0s - loss: 3.4350e-04
Epoch 11/20
0s - loss: 3.2451e-04
Epoch 12/20
0s - loss: 3.2447e-04
Epoch 13/20
0s - loss: 2.9842e-04
Epoch 14/20
0s - loss: 2.7896e-04
Epoch 15/20
0s - loss: 2.8764e-04
Epoch 16/20
0s - loss: 2.6778e-04
Epoch 17/20
0s - loss: 2.6490e-04
Epoch 18/20
0s - loss: 2.6062e-04
Epoch 19/20
0s - loss: 2.5999e-04
Epoch 20/20
0s - loss: 2.6229e-04
CPU times: user 5.38 s, sys: 625 ms, total: 6 s
Wall time: 4.89 s

In [7]:
%%time
# Estimate model performance
trainScore = model.evaluate(data_train, labels_train, verbose=0)
print('Train Score: %.2f MSE (%.2f RMSE)' % (trainScore, np.sqrt(trainScore)))
testScore = model.evaluate(data_test, labels_test, verbose=0)
print('Test Score: %.2f MSE (%.2f RMSE)' % (testScore, np.sqrt(testScore)))
fitness = 1 / (1+ testScore)
print('Fitness: %.7f  ' % (fitness))


Train Score: 0.00 MSE (0.02 RMSE)
Test Score: 0.00 MSE (0.05 RMSE)
Fitness: 0.9978552  
CPU times: user 484 ms, sys: 15.6 ms, total: 500 ms
Wall time: 446 ms

In [8]:
# generate predictions for training
trainPredict = model.predict(data_train) * data_maxmin + data_mean
testPredict = model.predict(data_test) * data_maxmin + data_mean
n_samples = data_train.shape[0] + data_test.shape[0]
# shift train predictions for plotting
trainPredictPlot = np.zeros((n_samples,1))
trainPredictPlot[:, :] = np.nan
trainPredictPlot[tau:len(trainPredict), :] = trainPredict[:-tau,:]
# shift test predictions for plotting
testPredictPlot = np.zeros((n_samples,1))
testPredictPlot[:, :] = np.nan
testPredictPlot[len(trainPredict)+(tau)+1:(n_samples), :] = testPredict[:-tau-1,:]
# plot baseline and predictions
sl= slice(0,1000)
plt.figure(figsize=(20,5))
plt.plot(data_final[data_final['Date'] > '2014-12-31']['Consommation'].values[sl])
plt.plot(trainPredictPlot[sl])
plt.plot(testPredictPlot[sl])
plt.show()


Genetic Algorithm


In [9]:
population_size = 4
max_generations = 2
crossover_weights = 0.9
bestfit = 1e-4 # not used
minF = 0.99 # not used

In [10]:
params = {'time_lags' : 48, 'hidden_units' : 20, 'training_algo' : "adam" }
params_minmax = {'time_lags' : [1, 10], 'hidden_units' : [1, 30], 'training_algo' : "adam" }

In [11]:
class Individual(object):
    """An individual in a population."""

    def __init__(self, vector):
        """Initialize with an encoded vector and fitness function."""
        self.phenotype = self.validate_vector(vector)
        print(self.phenotype)
        self.fitness = self.calculate_fitness()

    def validate_vector(self, vector, params_minmax= params_minmax):
        """Make sure all elements are between minmax"""
        validated_vector = {}
        for key in vector:
            if (vector[key] <= params_minmax[key][1]) & (vector[key] >= params_minmax[key][0]):
                validated_vector[key] = vector[key]
            else :
                validated_vector[key] = params_minmax[key][1]
                
        return validated_vector

    def calculate_fitness(self):
        """Get the individual's fitness. EXPENSIVE."""
        # run network 
        NN = NeuralNetwork(phenotype = self.phenotype)
        NN.fitness()
        
        return NN.fitness

In [12]:
class NeuralNetwork(object):
    
    def __init__(self, phenotype):
        self.phenotype = phenotype
        self.individual_trained = 0
        self.lags = int(phenotype['time_lags'])
    # create and fit Multilayer Perceptron model
    
    def train(self, X, Y) :
        pass
    
    def fitness(self) :
        X_train, Y_train = data_labels(dataframe = data_final[(data_final['Date'] <= '2015-01-31') & (data_final['Date'] > '2014-12-31')], tau=self.lags)
        X_test, Y_test = data_labels(dataframe = data_final[(data_final['Date'] > '2015-01-31') & (data_final['Date'] <= '2016-01-01')], tau=self.lags)
  
        model = Sequential()
        model.add(Dense(self.phenotype['hidden_units'], #parameter of each individual
                        input_dim=self.phenotype['time_lags'], #parameter of each individual
                        activation='relu'))
        model.add(Dense(1))
        model.compile(loss='mean_squared_error', optimizer='adam')
        model.fit(X_train, Y_train, nb_epoch=20, batch_size=30, verbose=2)

#             self.train(X= X_train, Y= Y_train)
        self.trainPredict = model.predict(X_train)
        self.testPredict = model.predict(X_test)
        self.trainScore = model.evaluate(X_train, Y_train, verbose=0)
        self.testScore = model.evaluate(X_test, Y_test, verbose=0)
        self.fitness = 1 / (1 + self.testScore)
        print("Fitness = %.2e" %(self.fitness))

In [13]:
# Initialize the population at t=0 - build list of Individual objects
class Population(object):
    
    def __init__(self, params, params_minmax):
        self.params = params
        self.params_minmax = params_minmax
    
        self.initial_population = []

        for individual in range(0, population_size):

            individual_dico = {}
            individual_dico.clear()

            individual_dico['hidden_units'] = np.random.randint(
                self.params_minmax['hidden_units'][0], self.params_minmax['hidden_units'][1])
            individual_dico['time_lags'] = np.random.randint(
                self.params_minmax['time_lags'][0], self.params_minmax['time_lags'][1])
#             print(individual_dico)
            new_individual = Individual(individual_dico)
            self.initial_population.append(new_individual)
            self.population = self.initial_population
        print("Population of %d individuals initialized" % (len(self.population)))
        
    def remove_worst_individual(self):
        all_fitness = [self.population[i].fitness for i in range(len(self.population))]

        del self.population[np.argmin(all_fitness)]

    def add_individual(self, popu):
        if len(popu) ==1 :
            self.population.append(popu[0])
        else :
            all_fitness = [popu[i].fitness for i in range(len(popu))]
            self.population.append(popu[np.argmax(all_fitness)])
            
    def global_fitness(self):
        return np.mean([self.population[i].fitness for i in range(len(self.population))])

In [14]:
class Evolution(object):
    
    def __init__(self, population_initiale, params_minmax= params_minmax, w=crossover_weights):
        self.population = population_initiale
        self.popu_size = len(population_initiale)
        self.params_minmax = params_minmax
        self.w = w
        
    
    def crossover_mutation(self):
        '''Function to perform cross-over and mutation'''
        
        # random selection of two parents 
        i, j = np.random.choice(np.arange(0,self.popu_size), 2, replace = False) 
        papa = self.population[i].phenotype
        self.nb_params = len(papa)
        maman = self.population[j].phenotype
        
        '''Crossover'''
        C = np.zeros((4, len(papa)))
        M = np.zeros(C.shape)
        for k, key in enumerate(papa):
            c1 = (papa[key] + maman[key])/2
            c2 = params_minmax[key][1] * (1-self.w) + max(papa[key], maman[key]) *self.w
            c3 = params_minmax[key][0] * (1-self.w) + min(papa[key], maman[key]) *self.w
            c4 = (params_minmax[key][1]- params_minmax[key][0]) * (1-self.w) +\
                (papa[key] + maman[key])/2
            
            C[0,k] = c1 
            C[1,k] = c2
            C[2,k] = c3
            C[3,k] = c4
            
            for l in range(4) :
                M[l,k] = np.random.randint(params_minmax[key][0]- C[l,k], \
                                    params_minmax[key][1]+ C[l,k])
        
        '''Mutation'''
        # 1st mutation 
        sig = np.zeros(len(papa))
        sig[np.random.choice(len(papa))]=1

        for l in range(4):
            self.Mutation1 = C[l,:] + np.multiply(M[l,:],sig)

        # 2nd mutation 
        sig = np.zeros(len(papa))
        sig[np.random.choice(len(papa),len(papa),replace=True)]=1

        for l in range(4):
            self.Mutation2 = C[l,:] + np.multiply(M[l,:],sig)

        # 3rd mutation 
        sig = np.ones(len(papa))

        for l in range(4):
            self.Mutation3 = C[l,:] + np.multiply(M[l,:],sig)
            
        self.Mutation = []
        self.Mutation = [self.Mutation1, self.Mutation2, self.Mutation3]
        
        '''return dictionnary of mutated chromosomes'''
        return self.convert_to_dict(np.rint(C)),\
                self.convert_to_dict(np.rint(self.Mutation)) \


    def convert_to_dict(self, vector):
        '''conversion of a vector to a phenotype dictionary'''
        n = vector.shape[0]
        key = [ 'time_lags', 'hidden_units',]
        return [dict(zip(key, np.atleast_2d(vector)[l,:]))  for l in range(np.atleast_2d(vector).shape[0])]

In [15]:
%%time 

'''Modified GA'''
num_generations = 0 
global_fitness=[]
global_population = []

'''initializing population'''
print("-"*78)
print(25*" "+"POPULATION INITIALIZATION ")
print("-"*78)

Population_ = Population(params,params_minmax)
global_population.append([Population_.initial_population[i].phenotype for i in range(len(Population_.population))])


'''Evaluate fitness for the initial population'''
global_fitness.append(Population_.global_fitness())

while num_generations < max_generations :
    
    num_generations +=1 
    
    Evo = Evolution(Population_.population)
    Evo.crossover_mutation()
    
    print("-"*78)
    print(25*" "+"CROSS-OVER %d" %(num_generations))
    print("-"*78)
    
    '''removing worst individual and add best crossover individual'''
    cross_over_popu = [Individual(Evo.crossover_mutation()[0][i]) \
                       for i in range(len(Evo.crossover_mutation()[0]))]

    Population_.remove_worst_individual()
    Population_.add_individual(popu = cross_over_popu)
    
    
    print("-"*78)
    print(25*" "+"MUTATION %d" %(num_generations))
    print("-"*78)
    
    '''mutation acceptance'''
    p_mutation = 0.1
    mutation_population = [Individual(Evo.crossover_mutation()[1][i]) for i in range(len(Evo.crossover_mutation()[1]))]

    for l in range(3):
        if np.random.rand() < p_mutation:
            print("Mutated Chromosome v1 %d " %l)
            Population_.remove_worst_individual()
            Population_.add_individual(popu = [mutation_population[l]])
        else:
            popu_fitness = [Population_.population[i].fitness for i in range(len(Population_.population))]
            if mutation_population[l].fitness > np.argmin(popu_fitness):
                print("Mutated Chromosome v2 %d " %l)
                Population_.remove_worst_individual()
                Population_.add_individual(popu = [mutation_population[l]])

        
    '''Evaluate fitness for the population'''
    global_fitness.append(Population_.global_fitness())
    global_population.append([Population_.population[i].phenotype for i in range(len(Population_.population))])


------------------------------------------------------------------------------
                         POPULATION INITIALIZATION 
------------------------------------------------------------------------------
{'hidden_units': 23, 'time_lags': 8}
Epoch 1/20
0s - loss: 0.0028
Epoch 2/20
0s - loss: 0.0019
Epoch 3/20
0s - loss: 0.0012
Epoch 4/20
0s - loss: 8.2728e-04
Epoch 5/20
0s - loss: 6.9500e-04
Epoch 6/20
0s - loss: 6.0542e-04
Epoch 7/20
0s - loss: 5.4719e-04
Epoch 8/20
0s - loss: 5.2003e-04
Epoch 9/20
0s - loss: 4.8389e-04
Epoch 10/20
0s - loss: 4.3802e-04
Epoch 11/20
0s - loss: 4.2271e-04
Epoch 12/20
0s - loss: 3.9947e-04
Epoch 13/20
0s - loss: 4.0204e-04
Epoch 14/20
0s - loss: 3.6520e-04
Epoch 15/20
0s - loss: 3.5723e-04
Epoch 16/20
0s - loss: 3.7365e-04
Epoch 17/20
0s - loss: 3.3912e-04
Epoch 18/20
0s - loss: 3.2782e-04
Epoch 19/20
0s - loss: 3.1940e-04
Epoch 20/20
0s - loss: 3.0754e-04
Fitness = 9.93e-01
{'hidden_units': 29, 'time_lags': 4}
Epoch 1/20
0s - loss: 0.0475
Epoch 2/20
0s - loss: 0.0049
Epoch 3/20
0s - loss: 0.0025
Epoch 4/20
0s - loss: 0.0015
Epoch 5/20
0s - loss: 7.6569e-04
Epoch 6/20
0s - loss: 4.8273e-04
Epoch 7/20
0s - loss: 3.7142e-04
Epoch 8/20
0s - loss: 3.1357e-04
Epoch 9/20
0s - loss: 2.9320e-04
Epoch 10/20
0s - loss: 2.9069e-04
Epoch 11/20
0s - loss: 3.0176e-04
Epoch 12/20
0s - loss: 2.7220e-04
Epoch 13/20
0s - loss: 2.6903e-04
Epoch 14/20
0s - loss: 2.6349e-04
Epoch 15/20
0s - loss: 2.6900e-04
Epoch 16/20
0s - loss: 2.5941e-04
Epoch 17/20
0s - loss: 2.6218e-04
Epoch 18/20
0s - loss: 2.5760e-04
Epoch 19/20
0s - loss: 2.5594e-04
Epoch 20/20
0s - loss: 2.5208e-04
Fitness = 9.96e-01
{'hidden_units': 6, 'time_lags': 6}
Epoch 1/20
0s - loss: 0.0036
Epoch 2/20
0s - loss: 0.0012
Epoch 3/20
0s - loss: 9.2895e-04
Epoch 4/20
0s - loss: 8.7414e-04
Epoch 5/20
0s - loss: 8.0969e-04
Epoch 6/20
0s - loss: 7.6274e-04
Epoch 7/20
0s - loss: 7.2357e-04
Epoch 8/20
0s - loss: 7.0097e-04
Epoch 9/20
0s - loss: 6.5219e-04
Epoch 10/20
0s - loss: 6.2192e-04
Epoch 11/20
0s - loss: 6.0418e-04
Epoch 12/20
0s - loss: 5.7498e-04
Epoch 13/20
0s - loss: 5.4421e-04
Epoch 14/20
0s - loss: 5.3432e-04
Epoch 15/20
0s - loss: 5.1866e-04
Epoch 16/20
0s - loss: 5.0268e-04
Epoch 17/20
0s - loss: 4.8235e-04
Epoch 18/20
0s - loss: 4.7419e-04
Epoch 19/20
0s - loss: 4.6212e-04
Epoch 20/20
0s - loss: 4.5954e-04
Fitness = 9.89e-01
{'hidden_units': 16, 'time_lags': 2}
Epoch 1/20
7s - loss: 0.0047
Epoch 2/20
1s - loss: 0.0012
Epoch 3/20
0s - loss: 9.7190e-04
Epoch 4/20
0s - loss: 8.7265e-04
Epoch 5/20
0s - loss: 8.2038e-04
Epoch 6/20
0s - loss: 7.8323e-04
Epoch 7/20
0s - loss: 7.3479e-04
Epoch 8/20
0s - loss: 7.0695e-04
Epoch 9/20
0s - loss: 6.6803e-04
Epoch 10/20
1s - loss: 6.3391e-04
Epoch 11/20
0s - loss: 6.0911e-04
Epoch 12/20
0s - loss: 5.6559e-04
Epoch 13/20
0s - loss: 5.3572e-04
Epoch 14/20
0s - loss: 5.0631e-04
Epoch 15/20
0s - loss: 4.8377e-04
Epoch 16/20
0s - loss: 4.5347e-04
Epoch 17/20
0s - loss: 4.3382e-04
Epoch 18/20
1s - loss: 3.9870e-04
Epoch 19/20
1s - loss: 3.8347e-04
Epoch 20/20
3s - loss: 3.5701e-04
Fitness = 9.96e-01
Population of 4 individuals initialized
------------------------------------------------------------------------------
                         CROSS-OVER 1
------------------------------------------------------------------------------
{'hidden_units': 6.0, 'time_lags': 10}
Epoch 1/20
5s - loss: 0.0078
Epoch 2/20
0s - loss: 0.0042
Epoch 3/20
0s - loss: 0.0024
Epoch 4/20
1s - loss: 0.0019
Epoch 5/20
1s - loss: 0.0017
Epoch 6/20
1s - loss: 0.0015
Epoch 7/20
1s - loss: 0.0013
Epoch 8/20
0s - loss: 0.0012
Epoch 9/20
1s - loss: 0.0011
Epoch 10/20
1s - loss: 9.6864e-04
Epoch 11/20
1s - loss: 8.7689e-04
Epoch 12/20
1s - loss: 8.1607e-04
Epoch 13/20
1s - loss: 7.3521e-04
Epoch 14/20
0s - loss: 6.8779e-04
Epoch 15/20
1s - loss: 6.4115e-04
Epoch 16/20
1s - loss: 6.2787e-04
Epoch 17/20
1s - loss: 5.9108e-04
Epoch 18/20
1s - loss: 5.7242e-04
Epoch 19/20
0s - loss: 5.5396e-04
Epoch 20/20
0s - loss: 5.3723e-04
Fitness = 9.91e-01
{'hidden_units': 8.0, 'time_lags': 10}
Epoch 1/20
9s - loss: 0.0754
Epoch 2/20
1s - loss: 0.0114
Epoch 3/20
5s - loss: 0.0034
Epoch 4/20
8s - loss: 0.0020
Epoch 5/20
3s - loss: 0.0016
Epoch 6/20
2s - loss: 0.0014
Epoch 7/20
6s - loss: 0.0012
Epoch 8/20
0s - loss: 0.0011
Epoch 9/20
0s - loss: 0.0010
Epoch 10/20
0s - loss: 9.7688e-04
Epoch 11/20
0s - loss: 8.9188e-04
Epoch 12/20
0s - loss: 8.3692e-04
Epoch 13/20
0s - loss: 8.0256e-04
Epoch 14/20
0s - loss: 7.3287e-04
Epoch 15/20
0s - loss: 6.8086e-04
Epoch 16/20
0s - loss: 6.3811e-04
Epoch 17/20
0s - loss: 6.0340e-04
Epoch 18/20
0s - loss: 5.7648e-04
Epoch 19/20
0s - loss: 5.5094e-04
Epoch 20/20
0s - loss: 5.3351e-04
Fitness = 9.99e-01
{'hidden_units': 2.0, 'time_lags': 10}
Epoch 1/20
0s - loss: 0.0196
Epoch 2/20
0s - loss: 0.0113
Epoch 3/20
0s - loss: 0.0096
Epoch 4/20
0s - loss: 0.0082
Epoch 5/20
0s - loss: 0.0069
Epoch 6/20
0s - loss: 0.0059
Epoch 7/20
0s - loss: 0.0052
Epoch 8/20
0s - loss: 0.0047
Epoch 9/20
0s - loss: 0.0044
Epoch 10/20
0s - loss: 0.0041
Epoch 11/20
0s - loss: 0.0038
Epoch 12/20
0s - loss: 0.0036
Epoch 13/20
0s - loss: 0.0034
Epoch 14/20
0s - loss: 0.0032
Epoch 15/20
0s - loss: 0.0030
Epoch 16/20
0s - loss: 0.0028
Epoch 17/20
0s - loss: 0.0026
Epoch 18/20
0s - loss: 0.0024
Epoch 19/20
0s - loss: 0.0023
Epoch 20/20
0s - loss: 0.0021
Fitness = 9.75e-01
{'hidden_units': 6.0, 'time_lags': 10}
Epoch 1/20
0s - loss: 0.4579
Epoch 2/20
0s - loss: 0.1995
Epoch 3/20
0s - loss: 0.0933
Epoch 4/20
0s - loss: 0.0497
Epoch 5/20
0s - loss: 0.0279
Epoch 6/20
0s - loss: 0.0169
Epoch 7/20
0s - loss: 0.0118
Epoch 8/20
0s - loss: 0.0095
Epoch 9/20
0s - loss: 0.0080
Epoch 10/20
0s - loss: 0.0068
Epoch 11/20
0s - loss: 0.0058
Epoch 12/20
0s - loss: 0.0050
Epoch 13/20
0s - loss: 0.0043
Epoch 14/20
0s - loss: 0.0037
Epoch 15/20
0s - loss: 0.0032
Epoch 16/20
0s - loss: 0.0028
Epoch 17/20
0s - loss: 0.0025
Epoch 18/20
0s - loss: 0.0022
Epoch 19/20
0s - loss: 0.0020
Epoch 20/20
0s - loss: 0.0017
Fitness = 9.95e-01
------------------------------------------------------------------------------
                         MUTATION 1
------------------------------------------------------------------------------
{'hidden_units': 7.0, 'time_lags': 10}
Epoch 1/20
1s - loss: 0.0044
Epoch 2/20
0s - loss: 0.0025
Epoch 3/20
0s - loss: 0.0022
Epoch 4/20
0s - loss: 0.0020
Epoch 5/20
0s - loss: 0.0018
Epoch 6/20
0s - loss: 0.0016
Epoch 7/20
0s - loss: 0.0013
Epoch 8/20
0s - loss: 0.0010
Epoch 9/20
0s - loss: 8.0218e-04
Epoch 10/20
0s - loss: 6.1865e-04
Epoch 11/20
0s - loss: 5.0083e-04
Epoch 12/20
0s - loss: 4.3150e-04
Epoch 13/20
0s - loss: 3.8566e-04
Epoch 14/20
0s - loss: 3.5481e-04
Epoch 15/20
0s - loss: 3.4262e-04
Epoch 16/20
0s - loss: 3.2885e-04
Epoch 17/20
0s - loss: 3.1643e-04
Epoch 18/20
0s - loss: 3.0392e-04
Epoch 19/20
0s - loss: 3.0140e-04
Epoch 20/20
0s - loss: 2.9452e-04
Fitness = 9.99e-01
{'hidden_units': 5.0, 'time_lags': 10}
Epoch 1/20
0s - loss: 0.0096
Epoch 2/20
0s - loss: 0.0068
Epoch 3/20
0s - loss: 0.0060
Epoch 4/20
0s - loss: 0.0053
Epoch 5/20
0s - loss: 0.0030
Epoch 6/20
0s - loss: 8.9424e-04
Epoch 7/20
0s - loss: 6.6361e-04
Epoch 8/20
0s - loss: 6.2550e-04
Epoch 9/20
0s - loss: 5.9857e-04
Epoch 10/20
0s - loss: 5.7870e-04
Epoch 11/20
0s - loss: 5.7110e-04
Epoch 12/20
0s - loss: 5.5777e-04
Epoch 13/20
0s - loss: 5.4987e-04
Epoch 14/20
0s - loss: 5.3720e-04
Epoch 15/20
0s - loss: 5.2746e-04
Epoch 16/20
0s - loss: 5.1889e-04
Epoch 17/20
0s - loss: 5.1516e-04
Epoch 18/20
0s - loss: 5.0199e-04
Epoch 19/20
0s - loss: 4.9488e-04
Epoch 20/20
0s - loss: 4.9469e-04
Fitness = 9.97e-01
{'hidden_units': 11.0, 'time_lags': 10}
Epoch 1/20
1s - loss: 0.0231
Epoch 2/20
0s - loss: 0.0053
Epoch 3/20
0s - loss: 0.0037
Epoch 4/20
0s - loss: 0.0030
Epoch 5/20
0s - loss: 0.0025
Epoch 6/20
0s - loss: 0.0021
Epoch 7/20
0s - loss: 0.0018
Epoch 8/20
0s - loss: 0.0015
Epoch 9/20
0s - loss: 0.0013
Epoch 10/20
0s - loss: 0.0011
Epoch 11/20
0s - loss: 9.4649e-04
Epoch 12/20
0s - loss: 8.0893e-04
Epoch 13/20
0s - loss: 7.1249e-04
Epoch 14/20
0s - loss: 6.1758e-04
Epoch 15/20
0s - loss: 5.6094e-04
Epoch 16/20
0s - loss: 5.1544e-04
Epoch 17/20
0s - loss: 4.7342e-04
Epoch 18/20
0s - loss: 4.4164e-04
Epoch 19/20
0s - loss: 4.2276e-04
Epoch 20/20
0s - loss: 4.0855e-04
Fitness = 9.77e-01
Mutated Chromosome v2 0 
------------------------------------------------------------------------------
                         CROSS-OVER 2
------------------------------------------------------------------------------
{'hidden_units': 7.0, 'time_lags': 10}
Epoch 1/20
0s - loss: 0.0242
Epoch 2/20
0s - loss: 0.0057
Epoch 3/20
0s - loss: 0.0051
Epoch 4/20
0s - loss: 0.0042
Epoch 5/20
0s - loss: 0.0022
Epoch 6/20
0s - loss: 0.0016
Epoch 7/20
0s - loss: 0.0013
Epoch 8/20
0s - loss: 0.0011
Epoch 9/20
0s - loss: 9.8510e-04
Epoch 10/20
0s - loss: 8.8591e-04
Epoch 11/20
0s - loss: 8.0710e-04
Epoch 12/20
0s - loss: 7.3338e-04
Epoch 13/20
0s - loss: 6.6870e-04
Epoch 14/20
0s - loss: 6.1908e-04
Epoch 15/20
0s - loss: 5.6647e-04
Epoch 16/20
0s - loss: 5.2287e-04
Epoch 17/20
0s - loss: 4.9015e-04
Epoch 18/20
0s - loss: 4.6216e-04
Epoch 19/20
0s - loss: 4.3200e-04
Epoch 20/20
0s - loss: 4.0969e-04
Fitness = 9.97e-01
{'hidden_units': 10.0, 'time_lags': 10.0}
Epoch 1/20
0s - loss: 0.1288
Epoch 2/20
0s - loss: 0.0122
Epoch 3/20
0s - loss: 0.0031
Epoch 4/20
0s - loss: 0.0019
Epoch 5/20
0s - loss: 0.0013
Epoch 6/20
0s - loss: 0.0011
Epoch 7/20
0s - loss: 9.2245e-04
Epoch 8/20
0s - loss: 8.5779e-04
Epoch 9/20
0s - loss: 8.0555e-04
Epoch 10/20
0s - loss: 7.9302e-04
Epoch 11/20
0s - loss: 7.5325e-04
Epoch 12/20
0s - loss: 7.2334e-04
Epoch 13/20
0s - loss: 7.0456e-04
Epoch 14/20
0s - loss: 6.9591e-04
Epoch 15/20
0s - loss: 6.8297e-04
Epoch 16/20
0s - loss: 6.7115e-04
Epoch 17/20
0s - loss: 6.5443e-04
Epoch 18/20
0s - loss: 6.5055e-04
Epoch 19/20
0s - loss: 6.3212e-04
Epoch 20/20
0s - loss: 6.3188e-04
Fitness = 9.98e-01
{'hidden_units': 4.0, 'time_lags': 7.0}
Epoch 1/20
0s - loss: 0.0482
Epoch 2/20
0s - loss: 0.0328
Epoch 3/20
0s - loss: 0.0226
Epoch 4/20
0s - loss: 0.0161
Epoch 5/20
0s - loss: 0.0117
Epoch 6/20
0s - loss: 0.0086
Epoch 7/20
0s - loss: 0.0064
Epoch 8/20
0s - loss: 0.0049
Epoch 9/20
0s - loss: 0.0038
Epoch 10/20
0s - loss: 0.0029
Epoch 11/20
0s - loss: 0.0024
Epoch 12/20
0s - loss: 0.0019
Epoch 13/20
0s - loss: 0.0016
Epoch 14/20
0s - loss: 0.0014
Epoch 15/20
0s - loss: 0.0012
Epoch 16/20
0s - loss: 0.0010
Epoch 17/20
0s - loss: 9.1896e-04
Epoch 18/20
0s - loss: 8.2491e-04
Epoch 19/20
0s - loss: 7.4744e-04
Epoch 20/20
0s - loss: 6.8567e-04
Fitness = 9.99e-01
{'hidden_units': 7.0, 'time_lags': 10}
Epoch 1/20
0s - loss: 0.0387
Epoch 2/20
0s - loss: 0.0060
Epoch 3/20
0s - loss: 0.0036
Epoch 4/20
0s - loss: 0.0025
Epoch 5/20
0s - loss: 0.0016
Epoch 6/20
0s - loss: 0.0010
Epoch 7/20
0s - loss: 6.8654e-04
Epoch 8/20
0s - loss: 5.6833e-04
Epoch 9/20
0s - loss: 4.8567e-04
Epoch 10/20
0s - loss: 4.2560e-04
Epoch 11/20
0s - loss: 3.9788e-04
Epoch 12/20
0s - loss: 3.4619e-04
Epoch 13/20
0s - loss: 3.2865e-04
Epoch 14/20
0s - loss: 3.0843e-04
Epoch 15/20
0s - loss: 3.0082e-04
Epoch 16/20
0s - loss: 2.9295e-04
Epoch 17/20
0s - loss: 2.9230e-04
Epoch 18/20
0s - loss: 2.9162e-04
Epoch 19/20
0s - loss: 2.8425e-04
Epoch 20/20
0s - loss: 2.7673e-04
Fitness = 9.87e-01
------------------------------------------------------------------------------
                         MUTATION 2
------------------------------------------------------------------------------
{'hidden_units': 17.0, 'time_lags': 9.0}
Epoch 1/20
0s - loss: 0.0831
Epoch 2/20
0s - loss: 0.0088
Epoch 3/20
0s - loss: 0.0059
Epoch 4/20
0s - loss: 0.0041
Epoch 5/20
0s - loss: 0.0020
Epoch 6/20
0s - loss: 9.5893e-04
Epoch 7/20
0s - loss: 6.0028e-04
Epoch 8/20
0s - loss: 4.6124e-04
Epoch 9/20
0s - loss: 4.0065e-04
Epoch 10/20
0s - loss: 3.6201e-04
Epoch 11/20
0s - loss: 3.4974e-04
Epoch 12/20
0s - loss: 3.3167e-04
Epoch 13/20
0s - loss: 3.1046e-04
Epoch 14/20
0s - loss: 2.9901e-04
Epoch 15/20
0s - loss: 2.9833e-04
Epoch 16/20
0s - loss: 2.9375e-04
Epoch 17/20
0s - loss: 2.8617e-04
Epoch 18/20
0s - loss: 2.8024e-04
Epoch 19/20
0s - loss: 2.8141e-04
Epoch 20/20
0s - loss: 2.7879e-04
Fitness = 9.92e-01
{'hidden_units': 24.0, 'time_lags': 10}
Epoch 1/20
0s - loss: 0.0471
Epoch 2/20
0s - loss: 0.0037
Epoch 3/20
0s - loss: 0.0020
Epoch 4/20
0s - loss: 0.0015
Epoch 5/20
0s - loss: 0.0012
Epoch 6/20
0s - loss: 0.0010
Epoch 7/20
0s - loss: 8.9333e-04
Epoch 8/20
0s - loss: 7.9953e-04
Epoch 9/20
0s - loss: 7.1100e-04
Epoch 10/20
0s - loss: 6.6413e-04
Epoch 11/20
0s - loss: 6.0394e-04
Epoch 12/20
0s - loss: 5.7496e-04
Epoch 13/20
0s - loss: 5.4010e-04
Epoch 14/20
0s - loss: 5.1073e-04
Epoch 15/20
0s - loss: 4.9575e-04
Epoch 16/20
0s - loss: 4.7966e-04
Epoch 17/20
0s - loss: 4.5660e-04
Epoch 18/20
0s - loss: 4.5515e-04
Epoch 19/20
0s - loss: 4.3616e-04
Epoch 20/20
0s - loss: 4.2733e-04
Fitness = 9.91e-01
{'hidden_units': 28.0, 'time_lags': 10}
Epoch 1/20
0s - loss: 0.0118
Epoch 2/20
0s - loss: 0.0046
Epoch 3/20
0s - loss: 0.0021
Epoch 4/20
0s - loss: 0.0010
Epoch 5/20
0s - loss: 6.6086e-04
Epoch 6/20
0s - loss: 5.7864e-04
Epoch 7/20
0s - loss: 5.3284e-04
Epoch 8/20
0s - loss: 4.8830e-04
Epoch 9/20
0s - loss: 4.6248e-04
Epoch 10/20
0s - loss: 4.4988e-04
Epoch 11/20
0s - loss: 4.2850e-04
Epoch 12/20
0s - loss: 4.1158e-04
Epoch 13/20
0s - loss: 4.0309e-04
Epoch 14/20
0s - loss: 3.9102e-04
Epoch 15/20
0s - loss: 3.8045e-04
Epoch 16/20
0s - loss: 3.8334e-04
Epoch 17/20
0s - loss: 3.6794e-04
Epoch 18/20
0s - loss: 3.5759e-04
Epoch 19/20
0s - loss: 3.6033e-04
Epoch 20/20
0s - loss: 3.5237e-04
Fitness = 9.88e-01
Mutated Chromosome v2 0 
CPU times: user 2min 23s, sys: 9.28 s, total: 2min 32s
Wall time: 4min 9s

In [16]:
plt.plot(global_fitness)
plt.title("Population Fitness at each generation")
plt.savefig("Population_fitness.png")



In [68]:
initial_popu = global_population[0]
final_population = global_population[-1]

In [71]:
df_ini = pd.DataFrame(initial_popu)
df_final = pd.DataFrame(final_population)

In [80]:
'''Plots of parameters for each individuals for initial population and finalpopulation'''
df_ini.plot(kind='scatter', x='hidden_units', y='time_lags', title='Initial Population')
plt.savefig("population_initiale.png")
df_final.plot(kind='scatter', x='hidden_units', y='time_lags',title='Final Population')
plt.savefig("population_finale.png")



In [ ]: